package com.example.secondhandshop.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.ImageResponseData;
import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.model.FileUploader;
import com.example.secondhandshop.model.ProductService;

import java.io.File;

public class PublicProductsActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_GET_CONTENT = 1;
    private static final int REQUEST_PERMISSION = 1;

    private Uri imageUri;
    private EditText editAddr, editContent, editImageCode, editPrice, editTypeId, editTypeName;
    private ImageButton btnChooseImage;
    private Button btnPublish;
    long imageCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_products);

        requestStoragePermission();

        initializeViews();
        setButtonListeners();
    }

    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
        }
    }

    private void initializeViews() {
        editAddr = findViewById(R.id.editAddr);
        editContent = findViewById(R.id.editContent);
        editPrice = findViewById(R.id.editPrice);
        editTypeId = findViewById(R.id.editTypeId);
        editTypeName = findViewById(R.id.editTypeName);
        btnChooseImage = findViewById(R.id.btnChooseImage);
        btnPublish = findViewById(R.id.btnPublish);
    }

    private void setButtonListeners() {
        btnChooseImage.setOnClickListener(v -> openImagePicker());
        btnPublish.setOnClickListener(v -> publishProduct());
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_GET_CONTENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_GET_CONTENT && resultCode == RESULT_OK) {
            imageUri = data.getData();
            if (imageUri != null) {
                runOnUiThread(() -> Toast.makeText(PublicProductsActivity.this, "已选择图片: " + imageUri, Toast.LENGTH_SHORT).show());
                String imageFilePath = getRealPathFromURI(imageUri);
                btnChooseImage.setImageURI(imageUri);
                Log.d("PublicProductsActivity", "文件路径1: " + imageFilePath);
                uploadImage(new File(imageFilePath));
            }
        }
    }

    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        try (Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                Log.d("PublicProductsActivity", "文件路径2: " + cursor.getString(column_index));
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(PublicProductsActivity.this, "获取图片路径失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
        return null;
    }

    private void uploadImage(File imageFile) {
        FileUploader fileUploader = new FileUploader();
        fileUploader.uploadFile(imageFile, new FileUploader.UploadCallback() {
            @Override
            public void onUploadSuccess(ImageResponseData imageResponseData) {
                runOnUiThread(() -> {
                    imageCode = imageResponseData.getImageCode();

                    Toast.makeText(PublicProductsActivity.this, "图片上传成功", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onUploadFailure(String error) {
                runOnUiThread(() -> Toast.makeText(PublicProductsActivity.this, error, Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void publishProduct() {
        Item item = new Item();
        item.setAddr(editAddr.getText().toString().trim());
        item.setContent(editContent.getText().toString().trim());
        item.setImageCode(imageCode);
        item.setPrice(Integer.parseInt(editPrice.getText().toString().trim()));
        item.setTypeId(Integer.parseInt(editTypeId.getText().toString().trim()));
        item.setTypeName(editTypeName.getText().toString().trim());
        item.setTuserId(624);

        ProductService productService = new ProductService();
        productService.addProduct(item, new ProductService.ProductCallback() {
            @Override
            public void onProductAdded(String message) {
                runOnUiThread(() -> {
                    Toast.makeText(PublicProductsActivity.this, message, Toast.LENGTH_SHORT).show();
                    resetFormFields();
                });
            }

            @Override
            public void onProductAddFailure(String error) {
                runOnUiThread(() -> Toast.makeText(PublicProductsActivity.this, error, Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void resetFormFields() {
        runOnUiThread(() -> {
            editAddr.setText("");
            editContent.setText("");
            editImageCode.setText("");
            editPrice.setText("");
            editTypeId.setText("");
            editTypeName.setText("");

            imageUri = null;
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "已获得读取外部存储权限", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "未获得读取外部存储权限", Toast.LENGTH_SHORT).show();
            }
        }
    }
}